package rabbitmq.simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ConsumerDemo {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        // 1. 创建连接⼯⼚
        ConnectionFactory factory = new ConnectionFactory();
        // 2. 设置参数
        factory.setHost("192.168.247.132");//ip 默认值localhost
        factory.setPort(5672); //默认值5672
        factory.setVirtualHost("rhm");//虚拟机名称, 默认 /
        factory.setUsername("admin");//⽤⼾名,默认guest
        factory.setPassword("admin");//密码, 默认guest
        // 3. 从连接工厂获得一个连接
        Connection connection = factory.newConnection();
        // 4. 创建channel通道
        Channel channel = connection.createChannel();
        // 5. 声明队列,如果没有⼀个hello 这样的⼀个队列, 会⾃动创建, 如果有, 则不创建
        channel.queueDeclare("hello", true, false, false, null);
        // 6. 接收消息, 并消费
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到消息: " + new String(body));
            }
        };
        channel.basicConsume("hello", true, consumer);     // 消费
        // 等待回调函数执⾏完毕之后, 关闭资源
        TimeUnit.SECONDS.sleep(5);
        // 7. 释放资源
        channel.close();
        connection.close();
    }
}

